/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-11-27 17:12:50
 ******************************************************************************/
package cn.com.xy.sms.util;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONObject;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import cn.com.xy.sms.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.pubinfo.NumNameManager;
import cn.com.xy.sms.sdk.db.entity.pubinfo.PubInfoManager;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetUtil;
import cn.com.xy.sms.sdk.net.util.SigntureUtil;
import cn.com.xy.sms.sdk.queue.SdkTaskQueue;
import cn.com.xy.sms.sdk.queue.TaskInfo;
import cn.com.xy.sms.sdk.service.pubInfo.PubInfoService;
import cn.com.xy.sms.sdk.ui.popu.util.ViewUtil;
import cn.com.xy.sms.sdk.util.FileUtils;
import cn.com.xy.sms.sdk.util.RecordFunctionUtil;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.XyUtil;
import cn.com.xy.sms.sdk.util.ConversationManager;
/*SDK-616 hewengao 20160918 start*/
import cn.com.xy.sms.sdk.threadpool.SmartSmsThreadPoolManager;
/*SDK-616 hewengao 20160918 end*/
public class PublicInfoParseManager {

    private static HashMap<String, Long> publicLoadTime = new HashMap<String, Long>();
//    static ExecutorService publicPool = Executors.newFixedThreadPool(1);
    public static long mins = 1L;

    
    private static boolean downloadLogo(String bizportUrl, String logoDir, String logoName) {
        if (!NetUtil.checkAccessNetWork(2)) {           
            return false;
        }
        
        int result = FileUtils.downFileAndVerifyWithMd5(bizportUrl, logoDir, logoName, true);
        if (result == 0) {
            // 下载成功           
            return true;
        } else {
            return false;
        }
    }
    
    private static File getLocalPublicLogoFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            return file;
        }
        
        return null;
    }
    
    public static File findLogoFile(final String logoName) {
        try {
            final String logoDir = Constant.getPath("duoqu_publiclogo");
            final String logoPath = logoDir + logoName;

            File file = getLocalPublicLogoFile(logoPath);
            if (file == null) {
                Long time = publicLoadTime.get(logoPath);
                if (time != null && (System.currentTimeMillis() < (time + DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_REDOWNLOAD_LOGO_INTERVAL, 60 * mins * 1000L)))) {                
                    return null;
                }

                final String bizport = NetUtil.BIZPORT_DOWN_URL + logoName;
                boolean result = downloadLogo(bizport, logoDir, logoName);
                if (result) {
                    file = getLocalPublicLogoFile(logoPath);
                } else {
                    publicLoadTime.put(logoPath, System.currentTimeMillis());
                }                
            }
            
            return file;
        } catch (Throwable t) {
            LogManager.e(Constant.TAG, "", t);
        } finally {
            Long time = publicLoadTime.get("runResourseQueue");
            if (time == null || (System.currentTimeMillis() > (time + DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_RUN_RESOURSE_QUEUE_CYCLE, 3600000L)))) {
                SdkTaskQueue.addTask(new TaskInfo(7));
                publicLoadTime.put("runResourseQueue", System.currentTimeMillis());
            }
        }

        SdkTaskQueue.addTask(new TaskInfo(12, "state",  String.valueOf(RecordFunctionUtil.COMPANY_LOGO_STATE)));//设置企业logo状态标记
        return null;
    }

    /**
     * 依据图片名称获取图片,图片名称由企业资料
     * 
     * @param ctx
     *            上下文
     * @param logoName
     *            图片名称可为空,当不为空时,可以优化查询速度
     * @param width
     *            图片宽度
     * @param height
     *            图片高度
     * @param extend
     *            扩展参数,目前为空
     * @param callBack
     *            可用存在网络访问,如果需要异步查询后得到结果,可以传递此参数, 回调的数据为 Bitmap
     * @return BitmapDrawable
     */
    public static BitmapDrawable findBitmapLogoByLogoName(final Context ctx, final String logoName, final int width, final int height, Map<String, String> extend, final SdkCallBack callBack) {
        BitmapDrawable dr = null;
        /*SDK-431 songzhirong 20160530 start*/
        String uuid = UUIDUtils.uniqId();
        try {
            ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.util.PublicInfoParseManager", "findBitmapLogoByLogoName",  ctx,  logoName, width, height, extend, callBack);
            /*SDK-431 songzhirong 20160530 end*/
            final String logoDir = Constant.getPath("duoqu_publiclogo");
            final String logoPath = logoDir + logoName;

            File file = new File(logoPath);

            if (file.exists()) {
                // 说明文件存在
                // BitmapFactory.deco
                dr = ViewUtil.createBitmapByPath2(ctx, file, width, height);
                if (dr != null) {
                    XyUtil.doXycallBackResult(callBack, dr);
                    return dr;
                } else {
                    publicLoadTime.put(logoPath, System.currentTimeMillis());
                    XyUtil.doXycallBackResult(callBack, null);
                    return null;
                }
            } else {

                Long time = publicLoadTime.get(logoPath);
                if (time != null && (System.currentTimeMillis() < (time + DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_REDOWNLOAD_LOGO_INTERVAL, 60 * mins * 1000L)))) {
                    XyUtil.doXycallBackResult(callBack, null);
                    return null;
                }

                final String bizport = NetUtil.BIZPORT_DOWN_URL + logoName;
                /*SDK-616 hewengao 20160918 start*/
//                SmartSmsThreadPoolManager.publicPool;
                SmartSmsThreadPoolManager.getLogoService().execute(new Runnable() {
                /*SDK-616 hewengao 20160918 end*/
                    @Override
                    public void run() {
                        try {
                            /*SDK-616 hewengao 20160918 start*/
                            SmartSmsThreadPoolManager.setThreadNameAndPriority(SmartSmsThreadPoolManager.TNAME_PUBLICPOOL,
                                android.os.Process.THREAD_PRIORITY_BACKGROUND);
                            /*SDK-616 hewengao 20160918 end*/
                            downAndCreateDrawable(ctx, bizport, logoDir, logoName, logoPath, width, height, callBack);
						} catch (Throwable e) {
							LogManager.e(Constant.TAG, e.getMessage(), e);
						}

                    }
                });

            }
        } catch (Throwable e) {
            // TODO: handle Throwable
        } finally {
            /*SDK-431 songzhirong 20160530 start*/
            ConversationManager.saveLogOut(uuid,"cn.com.xy.sms.util.PublicInfoParseManager", "findBitmapLogoByLogoName",  ctx,  logoName, width, height, extend, callBack,dr);
            /*SDK-431 songzhirong 20160530 end*/
            Long time = publicLoadTime.get("runResourseQueue");
            if (time == null || (System.currentTimeMillis() > (time + DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_RUN_RESOURSE_QUEUE_CYCLE, 3600000L)))) {
                SdkTaskQueue.addTask(new TaskInfo(7));
                publicLoadTime.put("runResourseQueue", System.currentTimeMillis());
            }
        }

        SdkTaskQueue.addTask(new TaskInfo(12, "state",  String.valueOf(RecordFunctionUtil.COMPANY_LOGO_STATE)));//设置企业logo状态标记
        return dr;
    }

    private static BitmapDrawable downAndCreateDrawable(Context ctx, String bizportUrl, String logoDir, String logoName, String logoPath, int width, int height, final SdkCallBack callBack) {
        BitmapDrawable dr = null;
        try {
            // 走cdn下载logo

            if (!NetUtil.checkAccessNetWork(2)) {
                if (callBack != null) {
                    callBack.execute(null);
                }
                return null;
            }
            publicLoadTime.put(logoPath, System.currentTimeMillis());
            /*SDK-470 hewengao 20160630 start*/
            int result = FileUtils.downFileAndVerifyWithMd5(bizportUrl, logoDir, logoName,true);
            /*SDK-470 hewengao 20160630 start*/
            if (result == 0) {// 下载成功
                publicLoadTime.remove(logoPath);
                dr = ViewUtil.createBitmapByPath2(ctx, logoPath, width, height);
                if (callBack != null) {
                    callBack.execute(dr);
                }
                if (dr != null) {
                    publicLoadTime.remove(logoPath);
                    // memoryCache.put(logoPath, dr);
                }
            } else {// 下载失败
                if (callBack != null) {
                    callBack.execute(null);
                }
            }
        } catch (Throwable e) {
            // TODO: handle Throwable
        }
        return dr;
    }

    /**
     * 依据号码获取公众号资料信息,包含号码分类信息
     * 
     * @param ctx
     * @param phoneNum
     *            号码
     * @param numType
     *            号码类型 1:接入码 2:电话号码
     * @param logoType
     *            1:方形 固定值,2:圆形
     * @param simIccid
     * @return
     */
    public static String getLogoNameByNum(final Context ctx, final String phoneNum, final int numType, final int logoType, final String simIccid, final Map<String, String> extend, final SdkCallBack callBack) {
        try {
            if (!SigntureUtil.checkChannelFuncPower(Constant.POWER_COMPANY_INFO)) {
                return null;
            }

            SdkCallBack mySdkCallBack = new SdkCallBack() {

                @Override
                public void execute(Object... obj) {
                    if (obj != null) {
                        try {
                            String publicInfo = (String) obj[0];
                            if (!StringUtils.isNull(publicInfo)) {
                                JSONObject publicInfoObj = new JSONObject(publicInfo);
                                if (publicInfoObj != null) {
                                    if (logoType == 1) {
                                        XyUtil.doXycallBack(callBack, publicInfoObj.optString("logo"));
                                    } else {
                                        XyUtil.doXycallBack(callBack, publicInfoObj.optString("logoc"));
                                    }
                                }
                            } else {
                                XyUtil.doXycallBack(callBack, "");
                            }

                        } catch (Throwable e) {
                            XyUtil.doXycallBack(callBack, "");
                        }

                    }

                }
            };
            String publicInfo = PubInfoService.queryPublicInfo(ctx, phoneNum, numType, simIccid, extend, mySdkCallBack);
            if (!StringUtils.isNull(publicInfo)) {
                JSONObject obj = new JSONObject(publicInfo);
                if (obj != null) {
                    if (logoType == 1) {
                        return obj.optString("logo");
                    } else {
                        return obj.optString("logoc");
                    }
                }
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "findBitmapLogoByLogoName", e);
        }
        return "";
    }

    /**   
     * @param ctx
     * @param phoneNum 号码
     * @param numType   号码类型 1:接入码 2:电话号码
     * @param logoType  1:方形 固定值,2:圆形
     * @param simIccid
     * @param extend
     * @param callBack 回调函数
     * @return JSONObject 返回企业名称和logo名称。name：企业名称，logoName，logo名称
     */
    public static JSONObject getNameAndLogoNameByNum(final Context ctx, final String phoneNum, final int numType, final int logoType, final String simIccid, final Map<String, String> extend, final SdkCallBack callBack) {
        try {
            if (!SigntureUtil.checkChannelFuncPower(Constant.POWER_COMPANY_INFO)) {
                return null;
            }
            SdkCallBack mySdkCallBack = null;
            if(callBack!=null){
            	mySdkCallBack = new SdkCallBack() {

                    @Override
                    public void execute(Object... obj) {
                        if (obj != null) {
                            try {
                                String publicInfo = (String) obj[0];
                                if (!StringUtils.isNull(publicInfo)) {
                                    JSONObject publicInfoObj = new JSONObject(publicInfo);
                                    if (publicInfoObj != null) {
                                        if (logoType == 1) {
                                            XyUtil.doXycallBackResult(callBack, getJSONObject("name",publicInfoObj.optString("name"),"logoName",publicInfoObj.optString("logo")));
                                        } else {
                                            XyUtil.doXycallBackResult(callBack, getJSONObject("name",publicInfoObj.optString("name"),"logoName",publicInfoObj.optString("logoc")));
                                        }
                                    }
                                } else {
                                    XyUtil.doXycallBack(callBack, null);
                                }

                            } catch (Throwable e) {
                                XyUtil.doXycallBack(callBack, null);
                            }

                        }

                    }
                };
            }  
            String publicInfo = PubInfoService.queryPublicInfo(ctx, phoneNum, numType, simIccid, extend, mySdkCallBack);
            if (!StringUtils.isNull(publicInfo)) {
                JSONObject obj = new JSONObject(publicInfo);
                if (obj != null) {
                    if (logoType == 1) {
//                        return obj.optString("logo");
                    	return getJSONObject("name",obj.optString("name"),"logoName",obj.optString("logo"));
                    } else {
//                        return obj.optString("logoc");
                    	return getJSONObject("name",obj.optString("name"),"logoName",obj.optString("logoc"));
                    }
                }
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "findBitmapLogoByLogoName", e);
        }
        return null;
    }
    
    public static JSONObject getJSONObject(String... result){    	
    	if(result==null||result.length<=0||result.length % 2!=0)return null;
		JSONObject json = new JSONObject();

    	try {
        	for(int i = 0; i < result.length; i+=2){
        		json.put(result[i], result[i+1]);
        	}
		} catch (Exception e) {
			// TODO: handle exception
		}    
    	return json;
    }

    /**
     * 依据号码，获取短信本地签名。
     * 
     * @param num
     * @return
     */
    public static String queryLocalSmsSignByNum(String num) {
        /* SDK-397 huangzhiqiang 20160524 start */
        String signName = NumNameManager.getLatestNumName(num);
        return signName == null ? "" : signName;
        /* SDK-397 huangzhiqiang 20160524 end */
    }

    /**
     * 根据企业号码获取企业企业logo图片资料
     * @param ctx
     * @param phoneNum
     * @param numType
     * @param logoType
     * @param simIccid
     * @param width
     * @param height
     * @param extend
     * @param callBack
     * @return
     */
    public static Drawable queryLogoByPhone(final Context ctx, final String phoneNum, final int numType, 
    		final int logoType, final String simIccid,
    		final int width, final int height, 
    		final Map<String, String> extend, final SdkCallBack callBack){
    	
    	try{
    		String logoName = getLogoNameByNum(ctx, phoneNum, numType, logoType, simIccid, extend, null);
        	if(logoName == null){
        		XyUtil.doXycallBackResult(callBack, "-1","logoName is null");
        		return null;
        	}
        	
        	BitmapDrawable drawable = findBitmapLogoByLogoName(ctx, logoName, width, height, extend, null);
        	if(drawable == null){
        		XyUtil.doXycallBackResult(callBack, "-1","logo drawable is null");
        		return null;
        	}else{
        		XyUtil.doXycallBackResult(callBack, "0", drawable);
        	}
        	return drawable;
    	}catch(Exception ex){
    		XyUtil.doXycallBackResult(callBack, "-1",ex.getLocalizedMessage());
    	}
    	return null;
    }
    
    /*SDK-727 zhaojiangwei 20170227 start */
    public static void clearPubInfoItemsNoBackColor() {
        SmartSmsThreadPoolManager.getLogoService().execute(new Runnable() {
            @Override
            public void run() {
                PubInfoManager.clearItemsWithoutBackColor();
            }
        });
    }
    /*SDK-727 zhaojiangwei 20170227 end */
}
